﻿@using System.ComponentModel.DataAnnotations;
@using System.ComponentModel
@using System.Reflection

<Form Model="@model"
      OnFinish="OnFinish"
      OnFinishFailed="OnFinishFailed"
      LabelColSpan="8"
      WrapperColSpan="16"
ValidateOnChange>

    @foreach (var field in fields)
    {
        <FormItem Name="@field.Key">
            @InputRender(field.Value)
        </FormItem>
    }

    <FormItem WrapperColOffset="8" WrapperColSpan="16">
        <Button Type="ButtonType.Primary" HtmlType="submit">
            Submit
        </Button>
    </FormItem>
</Form>

@code
{
    private Dictionary<string, PropertyInfo> fields = new();
    private Model model = new();

    protected override void OnInitialized()
    {
        fields = typeof(Model).GetProperties().ToDictionary(x => x.Name, x => x);
        base.OnInitialized();
    }

    public class Model
    {
        [Required, DisplayName("User Name")]
        public string Username { get; set; }

        [DisplayName("Birthday")]
        public DateOnly? Birthday { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [DisplayName("Password")]
        public string Password { get; set; }

        [DisplayName("RememberMe")]
        public bool RememberMe { get; set; } = true;
    }

    private RenderFragment InputRender(PropertyInfo property)
    {
        return property switch
        {
            _ when property.PropertyType.GetCustomAttribute<DataTypeAttribute>()?.DataType == DataType.Password =>@<InputPassword></InputPassword>,
            _ when property.PropertyType == typeof(bool) =>@<Checkbox></Checkbox>,
            _ when property.PropertyType == typeof(DateOnly?) =>@<DatePicker TValue="DateOnly?"></DatePicker>,
            _ =>@<Input TValue="string"></Input>,
        };
    }

    private void OnFinish(EditContext editContext)
    {
        Console.WriteLine($"Success:{JsonSerializer.Serialize(model)}");
    }

    private void OnFinishFailed(EditContext editContext)
    {
        Console.WriteLine($"Failed:{JsonSerializer.Serialize(model)}");
    }

    
}